const express = require("express")
const redis = require("redis")
const app = express()
const client = redis.createClient(6379, "0.0.0.0")
client.auth("123456")
app.use(express.json())
// 拾漂流瓶
let arr = ["male", "female"]
app.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "X-Requested-With")
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
  next()
})
app.get("/pickup", (req, res) => {
  let { user, type = "all" } = req.query
  if (type === "all") {
    let index = Math.round(Math.random())
    console.log("随机下表", index)
    type = arr[index] //如果是all则随机
  }
  client.srandmember(`bottles_${type}`, 1, (err, result) => {
    if (err) {
      res.json({
        code: 0,
        msg: err.message
      })
    } else {
      if (!result[0]) {
        res.json({ code: 0, msg: "大海上没有发现瓶子的踪迹！" })
      } else {
        let member = JSON.parse(result[0])
        res.json({
          code: 1,
          msg: "恭喜你，捡到一个漂流瓶",
          time: member.time,
          owner: member.owner,
          type: member.type,
          content: member.content
        })
      }
    }
  })
})
// 扔漂流瓶
app.post("/throw", (req, res, next) => {
  const { owner, content, type, time = new Date() } = req.query

  client.sadd(
    `bottles_${type}`,
    JSON.stringify({ owner, content, type, time }),
    (error) => {
      if (error) {
        res.status(200).json({
          code: 0,
          msg: error.message
        })
      }
      res.status(200).json({
        code: 1,
        msg: "成功了！"
      })
    }
  )
})
app.listen(3000, () => {
  console.log("app listenning at port 3000.")
})
